﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using AutoMapper;
using PagedList;
using SIG.Service;
using SIG.Model;

using SIG.WebMVC.Filters;
using SIG.Infrastructure.Configs;
using SIG.Infrastructure.Extensions;
using SIG.ViewModel.Admin.Links;
using SIG.InputModel.Admin.Links;
using SIG.ViewModel;
using System;
using SIG.Infrastructure.Helper;
using System.Xml.Linq;
using SIG.Resources.Admin;

namespace SIG.WebMVC.Areas.Admin.Controllers
{
    [SIGAuth]   
    public class LinkController : BaseController
    {
        private readonly ILinkCategoryService _categoryService;
        private readonly ILinkService _linkService;
        private readonly IPageMetaService _pageMetaService;
        private readonly IMapper _mapper;

        public LinkController(ILinkCategoryService categoryService,ILinkService linkService, IPageMetaService pageMetaService, IMapper mapper)
        {
            _categoryService = categoryService;
            _linkService = linkService;
            _pageMetaService = pageMetaService;
            _mapper = mapper;


        }
        #region Links
        

    [HttpGet]
        public ActionResult Index(int? page, int? categoryId, string Keyword)
        {

            var linkListVM = new LinkListVM();

            linkListVM.CategoryId = categoryId ?? 0;
            linkListVM.PageIndex = (page ?? 1) - 1;
            linkListVM.PageSize = SettingsManager.Link.PageSize;
            linkListVM.Keyword = Keyword;

            int count;
            var links = _linkService.GetPagedElements(linkListVM.PageIndex, linkListVM.PageSize, linkListVM.Keyword, linkListVM.CategoryId, out count);

            var linkDtos = _mapper.Map<List<Link>, List<LinkVM>>(links);

            //linkListVM.Links = linkDtos;
            linkListVM.TotalCount = count;

            var categoryList = _categoryService.GetAll().OrderByDescending(c => c.Importance).ToList();
            var categories = new SelectList(categoryList, "Id", "Title");
            ViewBag.Categories = categories;

            linkListVM.Links = new StaticPagedList<LinkVM>(linkDtos, linkListVM.PageIndex + 1, linkListVM.PageSize, linkListVM.TotalCount);
            // ViewBag.OnePageOfLinks = linksAsIPagedList;

            ViewBag.PageSizes = new SelectList(Site.PageSizes());

            return View(linkListVM);

        }


        [HttpPost]
        public JsonResult PageSizeSet(int pageSize)
        {
            try
            {
                var xmlFile = Server.MapPath("~/Config/LinkSettings.config");
                XDocument doc = XDocument.Load(xmlFile);

                var item = doc.Descendants("Settings").FirstOrDefault();
                item.Element("PageSize").SetValue(pageSize);
                doc.Save(xmlFile);

                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
        }




        public ActionResult Add()
        {
            var link = new LinkIM { Active = true };

            var categorys = _categoryService.GetAll().OrderByDescending(m => m.Importance).ToList();
            var lCategorys = new SelectList(categorys, "Id", "Title");

            ViewBag.Categories = lCategorys;
            return View(link);
        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Add(LinkIM link)
        {
            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            try
            {
                var newLink = _mapper.Map<LinkIM, Link>(link);
                _linkService.Create(newLink);

                AR.SetSuccess(String.Format(Messages.AlertCreateSuccess, EntityNames.Link));
                return Json(AR, JsonRequestBehavior.DenyGet);

            }
            catch (Exception er)
            {
                AR.Setfailure(er.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }


        }

        [HttpGet]
        public ActionResult Edit(int Id)
        {
            var vLink = _linkService.GetById(Id);
            if (vLink == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.AllowGet);
            }

            var editLink = _mapper.Map<Link, LinkIM>(vLink);

            var categorys = _categoryService.GetAll().OrderByDescending(m => m.Importance).ToList();
            var lCategorys = new SelectList(categorys, "Id", "Title");

            ViewBag.Categories = lCategorys;

            return View(editLink);


        }

        [HttpPost]       
        [ValidateAntiForgeryToken]
        public JsonResult Edit(LinkIM link)
        {
            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            try
            {
                var editLink = _mapper.Map<LinkIM, Link>(link);
                _linkService.Update(editLink);                      

                AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Link));
                return Json(AR, JsonRequestBehavior.DenyGet);

            }
            catch (Exception er)
            {
                AR.Setfailure(er.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }


        }


        //  [HttpPost]
        //  [ValidateAntiForgeryToken]
        //  public JsonResult Active(int id)
        //  {

        //      Link vLink = _linkService.GetById(id);            

        //      try
        //      {
        //          vLink.Active = !vLink.Active;
        //          _linkService.Update(vLink);

        //          var vm = _mapper.Map<LinkVM>(vLink);

        //          AR.Data = RenderPartialViewToString("_LinkItem", vm);
        //          AR.SetSuccess(String.Format(Resources.Messages.AlertUpdateSuccess, Resources.EntityNames.Link));
        //          return Json(AR, JsonRequestBehavior.DenyGet);

        //      }
        //      catch (Exception ex)
        //      {
        //          AR.Setfailure(ex.Message);
        //          return Json(AR, JsonRequestBehavior.DenyGet);
        //      }

        //  }

        //  [HttpPost]
        //  [ValidateAntiForgeryToken]
        //  public JsonResult Recommend(int id)
        //  {

        //      Link vLink = _linkService.GetById(id);

        //      try
        //      {
        //          vLink.Recommend = !vLink.Recommend;
        //          _linkService.Update(vLink);

        //          var vm = _mapper.Map<LinkVM>(vLink);
        //          AR.Data = RenderPartialViewToString("_LinkItem", vm);
        //          AR.SetSuccess(String.Format(Resources.Messages.AlertUpdateSuccess, Resources.EntityNames.Link));
        //          return Json(AR, JsonRequestBehavior.DenyGet);

        //      }
        //      catch (Exception ex)
        //      {
        //          AR.Setfailure(ex.Message);
        //          return Json(AR, JsonRequestBehavior.DenyGet);
        //      }

        //  }


        //  [HttpPost]       
        //  [ValidateAntiForgeryToken]
        //  public JsonResult Delete(int id)
        //  {

        //      Link vLink = _linkService.GetById(id);

        //      if (vLink == null)
        //      {
        //          AR.Setfailure(Resources.Messages.HttpNotFound);
        //          return Json(AR, JsonRequestBehavior.DenyGet);
        //      }

        //      _linkService.Delete(vLink);

        //      AR.SetSuccess(String.Format(Resources.Messages.AlertDeleteSuccess, Resources.EntityNames.Link));
        //      return Json(AR, JsonRequestBehavior.DenyGet);           

        //  }

        #endregion


    }
}
